package com.example.download2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

public class DownloadByAppacheHttp extends AsyncTask<String, Integer, Integer>{
	private Context mContext;
	private int mKey;
	private final static int faile=0;
	private final static int success=1;
	NotyManager no;
	
	public DownloadByAppacheHttp(Context context,NotyManager no) {
		mContext=context;
		this.no=no;
	}
	
	public void cancel()
	{
		this.cancel(true);
	}
	
	public void clearNotify()
	{
		no.clear(20);
	}
	@Override
	protected Integer doInBackground(String... params) {
		String url=params[0];
		HttpGet request=new HttpGet(url);
		long temp=0;
		File file=new File(Environment.getExternalStorageDirectory()+"/abc.apk");
		if(file.exists())
		{
			Log.d("Apache", "file exists");
			//addRequestHeaders(request, null,file.length()+"");
			request.addHeader("Range", "bytes=" + file.length() + "-");
			temp=file.length();
		}
		else
			addRequestHeaders(request, null,"0");
		
		AndroidHttpClient client=AndroidHttpClient.newInstance("AndroidDownloadManager",mContext);
		HttpResponse respone=null;
		try {
			respone=client.execute(request);
		} catch (IOException e) {
			e.printStackTrace();
			return faile;
		}
		
		if(respone==null)return faile;
		InputStream is=null;
		long sizetotal;
		try {
			is=respone.getEntity().getContent();
			sizetotal=respone.getEntity().getContentLength();
			Log.d("Total size=", sizetotal+"");
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return faile;
		} catch (IOException e) {
			e.printStackTrace();
			return faile;
		}
		
		if(is==null)return faile;
		FileOutputStream fos=null;
		try {
			fos=new FileOutputStream(file,true);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		byte[] b=new byte[1024];
		int length;
		
		try {
			while((length=is.read(b))!=-1)
			{
				fos.write(b, 0, length);
				temp+=length;
				//Log.d("ByApache", temp/sizetotal*100+"");
				notify(20, sizetotal, temp);
				if(isCancelled())break;
			}
			fos.flush();
			is.close();
			fos.close();
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(isCancelled())return faile;
		
		return success;
	}
	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);
		if(result==success)
		{
			Toast.makeText(mContext, "Thanh cong", Toast.LENGTH_LONG).show();
		}
		else
		{
			Toast.makeText(mContext, "Loi", Toast.LENGTH_LONG).show();
		}
	}
	
	
	private void addRequestHeaders(HttpGet request,String headerETag,String range)
	{
		/*if(headerETag!=null)
		{
			request.addHeader("If-Match", headerETag);
		}*/
		request.addHeader("Range", "bytes=" + range + "-");
	}
	
	public void notify(int id,long totalsize,long currentSize)
	{
		Notification n=new Notification();
		n.icon=android.R.drawable.stat_sys_download;
		n.flags|=Notification.FLAG_ONGOING_EVENT;
		
		 // Build the RemoteView object
        RemoteViews expandedView = new RemoteViews(mContext.getPackageName(),
                R.layout.status_bar_ongoing_event_progress_bar);
            expandedView.setTextViewText(R.id.description,
                    "download des");
        expandedView.setTextViewText(R.id.title, "download title");

            expandedView.setViewVisibility(R.id.paused_text, View.GONE);
            expandedView.setProgressBar(R.id.progress_bar,
                    (int) totalsize,
                    (int) currentSize,
                    totalsize == -1);
        expandedView.setTextViewText(R.id.progress_text,
                getDownloadingText(totalsize,currentSize));
        expandedView.setImageViewResource(R.id.appIcon, R.drawable.ic_launcher);
        n.contentView = expandedView;
        
        /*Intent intent = new Intent(Constants.ACTION_LIST);
        intent.setClassName(mContext.getPackageName(),
                DownloadReceiver.class.getName());
        intent.setData(
                ContentUris.withAppendedId(Downloads.ALL_DOWNLOADS_CONTENT_URI, item.mId));
        intent.putExtra("multiple", item.mTitleCount > 1);*/
        Intent intent=new Intent(mContext,DownloadReceiver.class);

        n.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
       // Log.e("DownloadNotification", "notify");
       // mSystemFacade.postNotification(item.mId, n);
        no.noty(id,n);
	}
	
	 /*
     * Helper function to build the downloading text.
     */
    private String getDownloadingText(long totalBytes, long currentBytes) {
        if (totalBytes <= 0) {
            return "";
        }
        long progress = currentBytes * 100 / totalBytes;
        StringBuilder sb = new StringBuilder();
        sb.append(progress);
        sb.append('%');
        return sb.toString();
    }
}

